package com.hackcloud.shardingjdbc.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.hackcloud.shardingjdbc.dao.sys",
        entityManagerFactoryRef = "defaultManagerFactoryBean",
        transactionManagerRef = "defaultTransactionManager")
public class DefaultDataSourceConfig {
    @Autowired
    JpaProperties jpaProperties;

    @Primary
    @Bean(name = "druidDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean defaultManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        final LocalContainerEntityManagerFactoryBean defaultPersistenceUnit = builder.dataSource(druidDataSource())
                .properties(jpaProperties.getProperties())
                .packages("com.hackcloud.shardingjdbc.domain.sys") //设置实体类所在位置
                .persistenceUnit("defaultPersistenceUnit")
                .build();
        defaultPersistenceUnit.setPersistenceUnitPostProcessors(pui -> pui.addProperty("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy"));
        return defaultPersistenceUnit;
    }

    @Primary
    @Bean(name = "defaultEntityManager")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return defaultManagerFactoryBean(builder).getObject().createEntityManager();
    }

    /**
     * 配置事物管理器
     *
     * @return
     */
    @Bean(name = "defaultTransactionManager")
    @Primary
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(defaultManagerFactoryBean(builder).getObject());
    }

}
